<template>
	<view class="box">
		<!-- 添加音乐主体 -->
		<view class="addAudio">
			<view class="back_image" v-if="!AudioY.audioUrl" @click="Audio_add('y')">
				<view class="back_image_content">
					<image src="../../static/tools/addaudio.png" mode=""></image>
				</view>
				<text>添加音频</text>
			</view>
			<view class="AudioFile" v-if="AudioY.audioUrl">
				<view class="AudioFile_left" @click="audio('y')">
					<image :src="isPlay1 == 0 ? '../../static/other/tz.png' : '../../static/other/bf.png'" mode="">
					</image>
				</view>
				<view class="AudioCentre">
					<view class="AudioCentre_top">{{ AudioY.audioName }}</view>
					<view class="AudioCentre_bottom">{{ AudioY.audioTime }}</view>
				</view>
				<view class="AudioFile_right" @click="Audio_add('y')">更换音频</view>
			</view>
		</view>
		<!--标题 -->
		<view class="title">
			<view class="title_left">
				<view class="title_a"></view>
				<view class="title_m"><text>音效选择</text></view>
			</view>
		</view>
		<uni-grid :column="4" :highlight='false' :showBorder="false">
			<uni-grid-item v-for="(item, index) in audioChangeList" :index="index" :key="index">
				<view :class="['grid-item-box', { actives: ActiveNum === index }]" style="background-color: #fff;"
					@tap="audioChange(index)">
					<img style="width: 115rpx; height: 115rpx;" :src="item.imgUrl">
					<div class="mask">
						<img src="../../static/other/audioChange.png" alt="">
					</div>
					<view class="text">{{item.text}}</view>
				</view>
			</uni-grid-item>
		</uni-grid>
		<view class="btn_box">
			<view class="btn_left">
				<u-button @click="synthesis(0)" size="large" type="primary" color="#5490FF" :plain="true" :text="text">
				</u-button>
			</view>
			<view class="btn_right">
				<u-button @click="synthesis(1)" size="large" type="primary" color="#5490FF" text="导出作品"></u-button>
			</view>
		</view>
		<!-- 导入方式 -->
		<u-popup :show="show" :round="18" @close="close" @open="open">
			<view class="u-popup_box">
				<view class="u-popup_">
					<u-button color="#5490FF" type="primary" text="微信对话中导入" @click="weixin"></u-button>
				</view>
				<view class="u-popup_">
					<u-button color="#5490FF" type="primary" text="取消" @click="close"></u-button>
				</view>
				<view class="title">
					注：支持
					<text>网易、qq、酷我</text>
					等主流音乐播放器导入音乐
				</view>
			</view>
		</u-popup>
		<!-- 非会员看广告提示 -->
		<u-modal :show="vipShow" :title="'温馨提示'" :content="'您还不是会员,此功能需开通会员或看广告才可使用。'" cancelText="看广告"
			confirmText="去开通" showCancelButton="true" @cancel="cancel" @confirm="govip" :closeOnClickOverlay="true"
			@close="vipShow=false"></u-modal>
	</view>
</template>

<script>
	import {
		isLogin,
		vipType
	} from '@/business/login.js';
	import {
		bsqUrl
	} from '@/api/assemb.js';
	import {
		uploadAudioFile
	} from '@/utils/upload/index.js';
	import {
		audioTypeJudgment
	} from '@/business/audioTypeJudgment.js';
	import store from "../../store/idnex.js";
	const innerAudioContext = wx.createInnerAudioContext(); // 创建内部 audio
	let app = getApp();
	// 在页面中定义激励视频广告
	let videoAd = null;
	export default {
		data() {
			return {
				show: false,
				AudioY: {
					audioUrl: '',
					audioName: '',
					audioTime: ''
				},
				compound: {},
				audioChangeList: [{
						imgUrl: '/static/icon/ys.png',
						text: '正常'
					},
					{
						imgUrl: '/static/icon/gx.png',
						text: '搞笑'
					},
					{
						imgUrl: '/static/icon/ds.png',
						text: '大叔'
					},
					{
						imgUrl: '/static/icon/li.png',
						text: '萝莉'
					},
					{
						imgUrl: '/static/icon/jqr.png',
						text: '机器人'
					},
					{
						imgUrl: '/static/icon/kl.png',
						text: '空灵'
					},
					{
						imgUrl: '/static/icon/hx.png',
						text: '混响'
					},
					{
						imgUrl: '/static/icon/kb.png',
						text: '恐怖'
					},
					{
						imgUrl: '/static/icon/xhr.png',
						text: '小黄人'
					},
					{
						imgUrl: '/static/icon/gc1.png',
						text: '广场'
					},
					{
						imgUrl: '/static/icon/sg.png',
						text: '山谷'
					},
					{
						imgUrl: '/static/icon/lt.png',
						text: '礼堂'
					}
				],
				ActiveNum: 0,
				isPlay1: 0,
				isPlay2: 0,
				text: '修改试听',
				duration: 0, // 总时长
				isAudition: 0, //是否试听过 试听过可以直接保存 和继续播放 、0是没有
				title: '修改名称',
				textValue: '音频变声',
				isAudio: '',
				mainPlay: false,
				isVip: false, //是否会员
				vipShow: false, // 激励广告是展示
				buttonID: -1, // 试听或保存
				isAd: false // 激励广告 观看是否成功
			};
		},
		watch: {
			ActiveNum(newValue, oldValue) {
				this.isAudition = 0;
				this.text = '修改试听';
			}
		},
		onLoad() {
			this.ad();
			if (uni.getStorageSync('audioFile')) {
				let isAudio = uni.getStorageSync('isAudio');
				let Audio = uni.getStorageSync('audioFile');
				if (uni.getStorageSync('AudioY')) {
					this.AudioY = uni.getStorageSync('AudioY');
				}
				if (isAudio == 'y') {
					this.AudioY = Audio;
					uni.setStorageSync('AudioY', Audio);
				}
				this.play2(Audio.audioUrl);
				uni.removeStorageSync('audioFile');
			}
		},
		onShow() {
			this.isVip = uni.getStorageSync('vipType').vipStatus == 1 ? true : false;
			// this.isVip = false;
		},
		onUnload() {
			if (this.mainPlay == true) {
				innerAudioContext.pause();
				this.isPlay1 = 0;
			}
		},
		onHide() {
			if (this.mainPlay == true) {
				innerAudioContext.pause();
				this.isPlay1 = 0;
			}
		},
		methods: {
			/**
			 * 音效选择
			 */
			audioChange(index) {
				this.ActiveNum = index
			},
			/**
			 * 广告初始化
			 */
			ad() {
				let _this = this;
				// 在页面onLoad回调事件中创建激励视频广告实例
				if (wx.createRewardedVideoAd) {
					videoAd = wx.createRewardedVideoAd({
						adUnitId: store.state.adUnitId
					});
					videoAd.onLoad(() => {});
					videoAd.onError(err => {});
					videoAd.onClose(res => {
						// 用户点击了【关闭广告】按钮
						if (res && res.isEnded) {
							_this.isAd = true;
							_this.synthesis(_this.buttonID);
							// 正常播放结束，可以下发游戏奖励
						} else {
							// 播放中途退出，不下发游戏奖励
						}
					});
				}
			},
			/**
			 * 跳转充值页面
			 */
			govip() {
				this.vipShow = false;
				if (uni.getStorageSync('OS') !== 'ios') {
					uni.navigateTo({
						url: '/pages/paymentCenter/paymentCenter'
					});
				} else {
					if (getApp().globalData.iosPay == 0) {
						uni.showModal({
							title: '提示',
							content: '由于相关规范，IOS功能暂不可用',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					} else if (getApp().globalData.iosPay == 1) {
						uni.navigateTo({
							url: '/pages/goods/goods'
						});
					}
				}
			},
			/**
			 * 观看广告触发
			 */
			cancel() {
				this.vipShow = false;
				// 用户触发广告后，显示激励视频广告
				if (videoAd) {
					videoAd.show().catch(() => {
						// 失败重试
						videoAd
							.load()
							.then(() => videoAd.show())
							.catch(err => {
								uni.showToast({
									title: "激励视频 广告显示失败",
									icon: 'none',
									duration: 2000
								})
							});
					});
				}
			},
			Audio_add(audio) {
				this.isAudio = audio;
				uni.setStorageSync('isAudio', audio);
				this.show = true;
			},

			neicun() {
				this.show = false;
				uni.redirectTo({
					url: '../memoryAdd/memoryAdd?url=https://mp3.peiyintek.cn/oss/index7.html'
				});
			},
			weixin() {
				this.show = false;
				let _this = this;
				uploadAudioFile().then(res => {
					if (_this.isAudio == 'y') {
						_this.AudioY = {
							audioUrl: res.audioUrl,
							audioName: res.audioName,
							audioTime: res.audioTime
						};
					}
					audioTypeJudgment(res.audioUrl).then(ser => {
						_this.audioIndex = 1;
						if (!!ser) {
							if (_this.isAudio == 'y') {
								_this.AudioY.audioUrl = ser;
								_this.play2(ser);
							} else {
								_this.AudioB.audioUrl = ser;
							}
						} else {
							if (_this.isAudio == 'y') {
								_this.AudioY.audioUrl = res.audioUrl;
								_this.play2(res.audioUrl);
							} else {
								_this.AudioB.audioUrl = res.audioUrl;
							}
						}
					});
				});
			},

			/** 合成
			 * @param {Object} buttonID 试听还是保存
			 */
			synthesis(buttonID) {
				if (this.AudioY.audioUrl != "") {
					this.buttonID = buttonID;
					if (this.isAudition != 0 || this.isAd || this.isVip) {
						this.isAd = false;
						if (buttonID == 0) {
							this.audio();
						} else {
							this.preserve();
						}
					} else {
						this.vipShow = true;
					}
				} else {
					uni.showToast({
						title: '请添加音频',
						duration: 2000,
						icon: 'none'
					});
				}
			},

			/*
			 *	@	保存
			 */
			preserve() {
				if (this.isAudition == 0) {
					this.compounds(this.AudioY.audioUrl, this.ActiveNum, 0);
				} else {
					this.share(this.compound.audioUrl)
				}
			},
			/*
			 *	@	初始音乐播放
			 */
			audio(data) {
				if (data == 'y') {
					this.play2(this.AudioY.audioUrl);
				} else {
					if (this.isAudition == 0) {
						this.compounds(this.AudioY.audioUrl, this.ActiveNum, 1);
					} else {
						this.play(this.compound.audioUrl);
					}
				}
			},
			/**
			 * @param {Object} mp3url
			 * @param {Object} bgmurl
			 * @param {Object} volume
			 * @param {Object} bgmVolume
			 * @param {Object} beforeTextTime
			 * @param {Object} afterTextTime
			 * @param {Object} musicSeconds
			 * @param {Object} isSudition
			 */
			compounds(ossUrl, type, isSudition) {
				const _this = this
				let param = {
					ossUrl: ossUrl,
					type: type
				};
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				bsqUrl(param, 1001, 'voiceChange').then(result => {
					uni.hideLoading()
					let compound = {
						audioUrl: result.serverUrl
					};
					_this.compound = compound;
					if (isSudition == 1) {
						_this.play(result.serverUrl);
					} else {
						_this.share(result.serverUrl)
					}
				});
			},
			share(url) {
				let _this = this;
				const houzhui = url.match(/\.[^.]+?$/)[0]; //后缀名的获取
				console.log(houzhui, '22222');
				const name = '音频变声'
				uni.showLoading({
					title: '下载中...',
					mask: true
				})
				wx.downloadFile({
					url: url, // 下载url
					filePath: wx.env.USER_DATA_PATH +
						"/weiYC" +
						name +
						houzhui,
					success(reslut) {
						// 下载完成后转发
						uni.showModal({
							title: '提示',
							content: '下载成功,点击分享保存',
							showCancel: false,
							confirmText: '分享',
							success: function(res) {
								console.log(res, 'res');
								if (res.confirm) {
									wx.shareFileMessage({
										filePath: reslut.filePath,
										fileName: name + houzhui,
										success(res) {
											console.log(res);
										},
										fail(err) {
											console.log(err);
										},
									});
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});

					},
					fail: console.error,
					complete() {
						wx.hideLoading()
					}
				});
			},
			/*
			 *	@	音频播放
			 */
			play(audioUrl) {
				console.log(audioUrl, 'audioUrl');
				if (this.isPlay2 != 0) {
					this.isPlay1 = 0;
					this.isPlay2 = 0;
					innerAudioContext.pause();
				} else {
					this.isPlay1 = 0;
					this.isPlay2 = 1;
					this.isAudition = 1;
					innerAudioContext.src = audioUrl;
					innerAudioContext.startTime = 0;
					innerAudioContext.play();
					this.text = '停止播放';
					innerAudioContext.onCanplay(() => {
						this.mainPlay = true;
						setTimeout(() => {
							innerAudioContext.currentTime;
							innerAudioContext.onTimeUpdate(() => {
								console.log('播放开始');
							});
							innerAudioContext.onEnded(res => {
								this.isPlay1 = 0;
								this.isPlay2 = 0;
								this.text = '继续播放';
							});
						}, 500);
					});
					innerAudioContext.onPause(() => {
						console.log('播放暂停了');
						//播放暂停
						this.isPlay1 = 0;
						this.isPlay2 = 0;
						this.text = '继续播放';
					});
				}
			},
			play2(audioUrl) {
				console.log(audioUrl, 'audioUrl');
				if (this.isPlay1 != 0) {
					this.isPlay1 = 0;
					innerAudioContext.pause();
				} else {
					this.isPlay1 = 1;
					innerAudioContext.src = audioUrl;
					innerAudioContext.startTime = 0;
					innerAudioContext.play();
					innerAudioContext.onCanplay(() => {
						setTimeout(() => {
							this.mainPlay = true;
							innerAudioContext.currentTime;
							innerAudioContext.onTimeUpdate(() => {
								console.log('播放开始');
								let Duration = innerAudioContext.duration;
								this.duration = parseInt(Duration);
							});
							innerAudioContext.onEnded(res => {
								this.isPlay1 = 0;
							});
						}, 500);
					});
					innerAudioContext.onPause(() => {
						console.log('播放暂停了');
						//播放暂停
						this.isPlay1 = 0;
					});
				}
			},
			open() {
				// console.log('open');
			},
			close() {
				this.show = false;
				// console.log('close');
			}
		}
	};
</script>

<style lang="scss" scoped>
	/deep/.grid-item-box {
		background-color: #f1f1f1 !important;
	}

	/deep/.u-button--plain {
		background-color: #f1f1f1 !important;
	}

	.actives .mask {
		opacity: 1;
	}

	.mask {
		position: absolute;
		width: 115rpx;
		height: 115rpx;
		opacity: 0;
	}

	.title {
		margin: auto;
		margin-top: 30rpx;
		margin-bottom: 30rpx;
		width: 676rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.title_left {
			display: flex;
			justify-content: left;
			align-items: center;

			.title_a {
				width: 6rpx;
				height: 30rpx;
				background-color: #5490FF;
				margin-right: 12rpx;
			}

			.title_m {
				font-size: 33rpx;
				font-weight: 500;
				color: #333333;
			}
		}
	}

	.AudioFile {
		width: 676rpx;
		height: 211rpx;
		background: #ffffff;
		border: 1rpx solid #5490FF;
		border-radius: 18rpx;
		display: flex;
		align-items: center;

		.AudioFile_left {
			width: 109rpx;
			height: 109rpx;
			margin-left: 22rpx;
			margin-right: 29rpx;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.AudioCentre {
			width: 325rpx;

			.AudioCentre_top {
				width: 260rpx;
				height: 54rpx;
				line-height: 54rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				font-size: 33rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #333333;
			}

			.AudioCentre_bottom {
				width: 260rpx;
				height: 54rpx;
				line-height: 54rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				font-size: 22rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #a8a8a8;
			}
		}

		.AudioFile_right {
			width: 157rpx;
			height: 54rpx;
			background: #ffffff;
			border: 2rpx solid #5490FF;
			border-radius: 27rpx;
			font-size: 24rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #5490FF;
			text-align: center;
			line-height: 54rpx;
		}
	}

	.back_image {
		width: 676rpx;
		height: 211rpx;
		background-image: url(../../static/tools/add_frame.png);
		background-size: 676rpx 211rpx;
		background-repeat: no-repeat;
		text-align: center;

		.back_image_content {
			image {
				display: inline-block;
				margin: auto;
				margin-top: 56rpx;
				margin-bottom: 26rpx;
				width: 60rpx;
				height: 60rpx;
			}
		}

		text {
			font-size: 25rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #5490FF;
		}
	}

	.u-popup_box {
		.u-popup_ {
			margin: 50rpx 66rpx;
		}

		.title {
			justify-content: center;
			text-align: center;
			font-size: 21rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #999999;
			line-height: 33rpx;

			text {
				color: #5490FF;
			}
		}
	}

	.grid-item-box {
		display: flex;
		flex-direction: column;
		align-items: center;

		img {
			width: 115rpx;
			height: 115rpx;
			margin-bottom: 20rpx
		}
	}

	.btn_box {
		background-color: #f1f1f1;
		position: fixed;
		bottom: 0rpx;
		left: 0rpx;
		display: flex;
		justify-content: space-around;
		height: 200rpx;
		width: 100%;

		.btn_left {
			/* 	background: #00cc6e; */
			margin-left: 33rpx;
			margin-top: 20rpx;
			width: 310rpx;
		}

		.btn_right {
			/* background: #358fff; */
			margin-right: 33rpx;
			margin-top: 20rpx;
			width: 310rpx;
		}
	}

	.addAudio {
		padding-top: 40rpx;
		display: flex;
		justify-content: center;
	}

	.Banner {
		width: 100%;
		margin-bottom: 30rpx;
	}

	.box {
		background: #f1f1f1;
		height: 100vh;
	}
</style>